package com.example.dingtalkwebproject.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.aliyun.dingtalkoauth2_1_0.models.GetSsoUserInfoHeaders;
import com.aliyun.dingtalkoauth2_1_0.models.GetSsoUserInfoRequest;
import com.aliyun.dingtalkoauth2_1_0.models.GetSsoUserInfoResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.example.dingtalkwebproject.pojo.CWeiXinConfigQy;
import com.example.dingtalkwebproject.pojo.dingUserInfo;
import com.example.dingtalkwebproject.service.CWeiXinConfigQyService;
import com.example.dingtalkwebproject.service.Sample;
import com.example.dingtalkwebproject.utils.AjaxResult;
import com.example.dingtalkwebproject.utils.DingTalkJsApiUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.aliyun.teaopenapi.models.Config;
import org.springframework.web.client.RestTemplate;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import static com.example.dingtalkwebproject.utils.DingTalkJsApiUtil.generateJsApiSignature;
import static com.example.dingtalkwebproject.utils.DingTalkTokenUtil.getAccessToken;

@RestController
@RequestMapping("/api")
public class dingTalkController {


    // agentid
    private final String agentId = "3845542052";
    // 企业Id
    private final String corpId = "ding5aa7a7ac34a9fb03";

    private final RestTemplate restTemplate;
    @Autowired
    private CWeiXinConfigQyService weiXinConfigQyService;

    public dingTalkController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    @GetMapping("/js-config")
    public AjaxResult getJsConfig(String url) {
        if (StringUtils.isBlank(url)) {
            return AjaxResult.error("未获取到前端路径信息!");
        }

        DingTalkJsApiUtil.JsApiSignature jsApiSignature = null;
        try {
            CWeiXinConfigQy cWeiXinConfigQy = weiXinConfigQyService.selectWeiXinConfigInfoByName();
            if (ObjectUtils.isEmpty(weiXinConfigQyService)) {
                return AjaxResult.error("未获取到当前残次报废的钉钉配置!");
            }
            // 不为空 那么就放置进去
            jsApiSignature = generateJsApiSignature(url, cWeiXinConfigQy.getJsApiTicket());
            if (ObjectUtils.isEmpty(jsApiSignature)) {
                return AjaxResult.error("未获取到JSAPI的ticket!");
            }
            Map<String, Object> config = new HashMap<>();
            config.put("agentId", agentId);
            config.put("corpId", corpId);
            config.put("timeStamp", jsApiSignature.getTimestamp());
            config.put("nonceStr", jsApiSignature.getNonceStr());
            config.put("signature", jsApiSignature.getSignature());
            return AjaxResult.success(config);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping("/userinfo/{authCode}")
    public AjaxResult getUserInfo(@PathVariable String authCode) throws Exception {
        // 参数校验
        if (StringUtils.isBlank(authCode))  {
            return AjaxResult.error(" 授权码格式错误");
        }

        // 获取钉钉配置信息（假设已正确获取）
        CWeiXinConfigQy cWeiXinConfigQy = weiXinConfigQyService.selectWeiXinConfigInfoByName();
        if (ObjectUtils.isEmpty(cWeiXinConfigQy))  {
            return AjaxResult.error(" 未获取到当前残次报废的钉钉配置!");
        }
        String accessToken = cWeiXinConfigQy.getAccessToken();

        // 构建请求
        try (CloseableHttpClient httpClient = HttpClients.createDefault())  {
            String url = "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo?access_token="  +
                         URLEncoder.encode(accessToken,  StandardCharsets.UTF_8.toString());
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type",  "application/json; charset=UTF-8");

            // 请求体
            JSONObject requestBody = new JSONObject();
            requestBody.put("code",  authCode);
            StringEntity entity = new StringEntity(requestBody.toString(),  StandardCharsets.UTF_8);
            httpPost.setEntity(entity);

            // 执行请求
            return httpClient.execute(httpPost,  response -> {
                int statusCode = response.getCode();  // 修正：response.getCode()  应为 response.getStatusLine().getStatusCode()
                String responseBody = EntityUtils.toString(response.getEntity());
                System.out.println(" 请求URL: " + url);
                System.out.println(" 请求体: " + requestBody);
                System.out.println(" 响应状态码: " + statusCode);
                System.out.println(" 响应体: " + responseBody);

                JSONObject jsonResponse = JSON.parseObject(responseBody);
                if (jsonResponse.getInteger("errcode")  == 0) {
                    // 解析 result 字段
                    JSONObject result = jsonResponse.getJSONObject("result");
                    // 创建 dingUserInfo 对象并赋值
                    dingUserInfo userInfo = new dingUserInfo();
                    userInfo.setUserId(result.getString("userid"));  // 注意字段名是 userid
                    userInfo.setUserName(result.getString("name"));
                    // corpName 需要其他接口补充（如部门查询接口）
                    return AjaxResult.success(userInfo);
                } else {
                    String errmsg = jsonResponse.getString("errmsg");
                    if ("invalid code".equals(errmsg)) {
                        return AjaxResult.error(" 授权码已失效，请重新获取");
                    }
                    return AjaxResult.error(errmsg);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(" 系统繁忙，请稍后重试: " + e.getMessage());
        }
    }
}
